#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include "cJSON/cJSON.h"  // 假设cJSON.h在cjson子目录，或根据实际路径调整

/**
 * 初始化串口（适配DL-30无线模块）
 */
int uart_init() {
    int fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd < 0) {
        printf("Content-Type: application/json\n\n");
        printf("{\"status\":\"error\",\"msg\":\"串口打开失败\"}");
        exit(1);
    }

    struct termios opt;
    tcgetattr(fd, &opt);
    cfsetispeed(&opt, B115200);
    cfsetospeed(&opt, B115200);

    opt.c_cflag |= (CLOCAL | CREAD);
    opt.c_cflag &= ~CSIZE;
    opt.c_cflag |= CS8;
    opt.c_cflag &= ~PARENB;
    opt.c_cflag &= ~CSTOPB;
    opt.c_cflag &= ~CRTSCTS;

    tcsetattr(fd, TCSANOW, &opt);
    return fd;
}

/**
 * 向STM32发送JSON命令并接收响应
 */
char* send_to_stm32(int uart_fd, const char* json_str) {
    static char resp[128] = {0};
    memset(resp, 0, sizeof(resp));

    // 格式：@JSON\n（符合STM32原有的@开头、\n结尾规则）
    char full_cmd[128];
    snprintf(full_cmd, sizeof(full_cmd), "@%s\n", json_str);
    write(uart_fd, full_cmd, strlen(full_cmd));

    usleep(100000);
    read(uart_fd, resp, sizeof(resp)-1);

    return resp;
}

int main() {
    printf("Content-Type: application/json\n\n");

    // 读取POST的JSON数据
    char post_data[128] = {0};
    int len = read(STDIN_FILENO, post_data, sizeof(post_data)-1);
    if (len <= 0) {
        printf("{\"status\":\"error\",\"msg\":\"无数据接收\"}");
        return 0;
    }

    // 用cJSON解析JSON
    cJSON *json = cJSON_Parse(post_data);
    if (!json) {
        printf("{\"status\":\"error\",\"msg\":\"JSON解析失败\"}");
        return 0;
    }

    // 提取device_id和degree
    cJSON *device_id = cJSON_GetObjectItem(json, "device_id");
    cJSON *degree = cJSON_GetObjectItem(json, "degree");
    
    if (device_id && degree && cJSON_IsNumber(device_id) && cJSON_IsNumber(degree)) {
        int dev_id = device_id->valueint;
        int deg = degree->valueint;

        // 初始化串口
        int uart_fd = uart_init();
        if (uart_fd < 0) {
            cJSON_Delete(json);
            return 0;
        }

        // 构造要发送到STM32的JSON（这里假设风扇逻辑，可根据实际需求修改）
        cJSON *stm32_json = cJSON_CreateObject();
        cJSON_AddNumberToObject(stm32_json, "device_id", dev_id);
        cJSON_AddNumberToObject(stm32_json, "degree", deg);
        char *json_str = cJSON_PrintUnformatted(stm32_json);

        // 发送到STM32
        char* stm32_resp = send_to_stm32(uart_fd, json_str);

        // 释放资源
        cJSON_Delete(stm32_json);
        free(json_str);
        close(uart_fd);
        cJSON_Delete(json);

        // 输出响应
        printf("{\"status\":\"success\",\"resp\":\"%s\"}", stm32_resp);
    } else {
        cJSON_Delete(json);
        printf("{\"status\":\"error\",\"msg\":\"JSON字段错误\"}");
    }

    return 0;
}
